package com.example.idea.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.idea.entity.Dao.UserDao;
import com.example.idea.entity.User;
import com.example.idea.exception.ServiceException;
import com.example.idea.service.UserService;
import com.example.idea.utils.Page;
import com.example.idea.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    /**
     * 新增用户
     */
    @RequestMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.add(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error(500, "用户名重复，请检查后重新添加用户");
            }
        }
        return Result.success(user);
    }

    /**
     * 修改用户
     */
    @RequestMapping("/update")
    public Result update(@RequestBody User user) {
        log.info("修改用户:{}", user);
        userService.update(user);
        return Result.success(user);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        userService.delete(id);
        return Result.success(null);
    }

    /**
     * 查询用户
     */
    @RequestMapping("/query/{id}")
    public Result query(@RequestParam Integer id) {
        User user = userService.query(id);
        return Result.success(user);
    }

    /**
     * 批量删除语句
     */
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        userService.deleteBatch(ids);
        return Result.success(null);
    }

    /**
     * 查询全部信息
     */
    @RequestMapping("/list")
    public Result list() {
        log.info("查询全部用户信息");
        List<User> users = userService.list();
        return Result.success(users);
    }

    /**
     * 根据不同条件进行查询数据
     */
    @RequestMapping("/selectList")
    public Result list(@RequestBody User user) {
        List<User> users = userService.selectList(user);
        return Result.success(users);
    }

    /**
     * 分页查询语句
     */
    @RequestMapping("/page")
    public Result page(@RequestBody User user) {
        List<User> page = userService.page(user);
        return Result.success(page);
    }

    @RequestMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String username,
                               @RequestParam String name) {
        log.info("分页查询，页码：{},页大小：{},用户名：{},姓名：{}", pageNum, pageSize, username, name);
        Page<User> page = userService.selectByPage(pageNum, pageSize, username, name);
        return Result.success(page);
    }

    /**
     * 忘记密码，验证用户名和手机号
     */
    @RequestMapping("/forget")
    public Result forget(@RequestBody UserDao user) {
        log.info("用户名:{},手机号:{}", user.getUsername(), user.getPhone());
        if (user.getUsername() == null || user.getPhone() == null) {
            return Result.failure("用户名或手机号错误");
        }
        userService.forgetUsernameAndPassword(user);
        return Result.success("ok");
    }

    /**
     * 批量导出数据
     */
    @RequestMapping("/export")
    public void export(@RequestParam(required = false) String username,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String ids,
                       HttpServletResponse response) throws IOException {
        log.info("导出数据。用户名:{},姓名:{}", username, name);
        ExcelWriter writer = ExcelUtil.getWriter(true);

        if (StrUtil.isNotBlank(ids)) {
            List<Integer> id = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            List<User> list1 = new ArrayList<>();
            id.forEach(id1 -> {User user = userService.query(id1);list1.add(user);});
            writer.write(list1,true);
        } else if(StrUtil.isNotBlank(username) || StrUtil.isNotBlank(name)) {
            List<User> list2 = userService.selectListAll(username, name);
            writer.write(list2,true);
        } else if (StrUtil.isBlank(username) && StrUtil.isBlank(name)) {
            List<User> list3 = userService.list();
            writer.write(list3,true);
        }
//        设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName +".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }

    /**
     * 批量导入
     */
    @RequestMapping("/import")
    public Result imp(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> userList = reader.readAll(User.class);
//        遍历userList一条一条插入
        userList.forEach(user -> {
            try {
                userService.addInfo(user);
            } catch (Exception e) {
                log.error("导入数据错误，请检查!", e);
                throw new ServiceException("导入数据错误，请检查!");
            }
        });
        return Result.success(userList);
    }
}
